import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Tabs, 
  Avatar, 
  Button, 
  List, 
  Tag, 
  Space, 
  Row, 
  Col,
  Statistic,
  message
} from 'antd';
import {
  UserOutlined,
  HistoryOutlined,
  HeartOutlined,
  SettingOutlined,
  WalletOutlined,
  StarOutlined,
  EditOutlined,
  ShoppingOutlined
} from '@ant-design/icons';
import '../styles/UserProfile.css';

const { TabPane } = Tabs;

const UserProfile = ({ initialTab = '1' }) => {
  const [activeTab, setActiveTab] = useState(initialTab);
  const [userInfo, setUserInfo] = useState(null);
  const [orders, setOrders] = useState([]);
  const [favorites, setFavorites] = useState([]);

  // 优先从localStorage读取用户信息
  useEffect(() => {
    let storedUserInfo = null;
    try {
      storedUserInfo = JSON.parse(localStorage.getItem('userInfo'));
    } catch (e) {}
    if (storedUserInfo && storedUserInfo.username) {
      setUserInfo(storedUserInfo);
    } else {
      // fallback: 兼容老逻辑
      // 模拟用户信息
      const mockUserInfo = {
        id: 1,
        username: '张三',
        avatar: null,
        email: 'zhangsan@example.com',
        phone: '138****5678',
        memberLevel: '黄金会员',
        points: 2580,
        wallet: 356.5,
        watchedCount: 25,
        favoriteCount: 8
      };
      setUserInfo(mockUserInfo);
    }

    // 模拟订单数据
    const mockOrders = [
      {
        id: 'ORDER20240306001',
        movieName: '流浪地球2',
        cinema: '万达影城（XX店）',
        datetime: '2024-03-06 14:30',
        seats: ['7排8座', '7排9座'],
        amount: 76.00,
        status: 'completed',
        orderTime: '2024-03-05 20:15'
      },
      {
        id: 'ORDER20240305001',
        movieName: '满江红',
        cinema: '博纳国际影城（XX店）',
        datetime: '2024-03-05 19:30',
        seats: ['5排12座'],
        amount: 45.00,
        status: 'completed',
        orderTime: '2024-03-04 18:20'
      },
      {
        id: 'ORDER20240304001',
        movieName: '熊出没·逆转时空',
        cinema: 'CGV影城（XX店）',
        datetime: '2024-03-04 10:30',
        seats: ['4排5座', '4排6座', '4排7座'],
        amount: 114.00,
        status: 'completed',
        orderTime: '2024-03-03 15:40'
      }
    ];
    setOrders(mockOrders);

    // 模拟收藏数据
    const mockFavorites = [
      {
        id: 1,
        type: 'movie',
        title: '流浪地球2',
        image: '/images/movie-poster1.jpg',
        rating: 4.8,
        date: '2024-03-01'
      },
      {
        id: 2,
        type: 'cinema',
        title: '万达影城（XX店）',
        image: '/images/cinema1.jpg',
        rating: 4.5,
        date: '2024-03-02'
      }
    ];
    setFavorites(mockFavorites);
  }, []);

  // 更新标签页
  useEffect(() => {
    setActiveTab(initialTab);
  }, [initialTab]);

  // 处理头像上传
  const handleAvatarUpload = () => {
    message.info('头像上传功能开发中...');
  };

  // 处理编辑个人信息
  const handleEditProfile = () => {
    message.info('编辑个人信息功能开发中...');
  };

  if (!userInfo) {
    return <div>Loading...</div>;
  }

  return (
    <div className="user-profile">
      {/* 用户基本信息卡片 */}
      <Card className="user-info-card">
        <Row gutter={24}>
          <Col span={6}>
            <div className="avatar-section">
              <Avatar 
                size={120} 
                icon={<UserOutlined />} 
                src={userInfo.avatar}
                className="user-avatar"
              />
              <Button 
                type="link" 
                icon={<EditOutlined />}
                onClick={handleAvatarUpload}
              >
                更换头像
              </Button>
            </div>
          </Col>
          <Col span={12}>
            <div className="user-details">
              <div className="username">
                {userInfo.username}
                {userInfo.memberLevel && <Tag color="gold" style={{ marginLeft: 8 }}>{userInfo.memberLevel}</Tag>}
              </div>
              <div className="user-contact">
                <p><strong>邮箱：</strong>{userInfo.email}</p>
                <p><strong>手机：</strong>{userInfo.phone}</p>
              </div>
              <Button 
                type="primary" 
                icon={<EditOutlined />}
                onClick={handleEditProfile}
              >
                编辑资料
              </Button>
            </div>
          </Col>
          <Col span={6}>
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              <Statistic 
                title="我的积分" 
                value={userInfo.points || 0} 
                prefix={<StarOutlined />} 
              />
              <Statistic 
                title="账户余额" 
                value={userInfo.wallet || 0} 
                precision={2} 
                prefix="¥" 
              />
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 标签页内容 */}
      <Card className="user-content-card">
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          className="user-tabs"
        >
          {/* 观影历史 */}
          <TabPane 
            tab={
              <span>
                <HistoryOutlined />
                观影历史
              </span>
            } 
            key="1"
          >
            <List
              className="order-list"
              itemLayout="vertical"
              dataSource={orders}
              renderItem={order => (
                <List.Item>
                  <Card className="order-card">
                    <div className="order-header">
                      <div className="order-id">订单号：{order.id}</div>
                      <Tag color={order.status === 'completed' ? 'green' : 'gold'}>
                        {order.status === 'completed' ? '已完成' : '待支付'}
                      </Tag>
                    </div>
                    <div className="order-content">
                      <div className="order-info">
                        <h4>{order.movieName}</h4>
                        <p>{order.cinema}</p>
                        <p>观影时间：{order.datetime}</p>
                        <p>座位：{order.seats.join('、')}</p>
                      </div>
                      <div className="order-amount">
                        <div className="amount">¥{order.amount.toFixed(2)}</div>
                        <div className="order-time">{order.orderTime}</div>
                      </div>
                    </div>
                  </Card>
                </List.Item>
              )}
            />
          </TabPane>

          {/* 我的收藏 */}
          <TabPane 
            tab={
              <span>
                <HeartOutlined />
                我的收藏
              </span>
            } 
            key="2"
          >
            <List
              grid={{ gutter: 16, column: 3 }}
              dataSource={favorites}
              renderItem={item => (
                <List.Item>
                  <Card 
                    hoverable 
                    cover={<img alt={item.title} src={item.image} />}
                    className="favorite-card"
                  >
                    <Card.Meta
                      title={item.title}
                      description={
                        <Space direction="vertical">
                          <Tag color={item.type === 'movie' ? 'blue' : 'cyan'}>
                            {item.type === 'movie' ? '电影' : '影院'}
                          </Tag>
                          <div>评分：{item.rating}</div>
                          <div>收藏时间：{item.date}</div>
                        </Space>
                      }
                    />
                  </Card>
                </List.Item>
              )}
            />
          </TabPane>

          {/* 优惠券 */}
          <TabPane 
            tab={
              <span>
                <ShoppingOutlined />
                我的优惠券
              </span>
            } 
            key="3"
          >
            <div className="coupons-empty">
              暂无可用优惠券
            </div>
          </TabPane>

          {/* 账户设置 */}
          <TabPane 
            tab={
              <span>
                <SettingOutlined />
                账户设置
              </span>
            } 
            key="4"
          >
            <div className="settings-content">
              账户设置功能开发中...
            </div>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default UserProfile; 